package com.github.monoliths_uni.tankcontrol.control;

import androidx.annotation.Nullable;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSink;

public class HttpController {

    static String HttpHost = "http://192.168.4.1/control";

    /**
     * Entry Issue
     */
    volatile boolean requestStatus = false;


    volatile boolean waitEndFlash = false;

    synchronized private void sendRequest(String data)
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //创建OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();

                    //创建Request
                    MediaType DATA_TYPE = MediaType.parse("text/xml; charset=utf-8");
                    RequestBody body = RequestBody.create(DATA_TYPE, data);

                    Request request = new Request.Builder()
                            .url(HttpHost) // 访问连接
                            .post(body)
                            .addHeader("Connection", "close")
                            .build();
                    // 创建Call对象
                    Call call = client.newCall(request);
                    //通过execute()方法获得请求响应的Response对象
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        //处理网络请求的响应，处理UI需要在UI线程中处理
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    requestStatus = false;
                }
            }
        }).start();
    }

    synchronized public void sendData(String data)
    {
        if (requestStatus)
        {
            return;
        }
        requestStatus = true;
        sendRequest(data);
    }



    synchronized public void endSignalSendData(String data)
    {
        if (waitEndFlash)
        {
            return;
        }
        waitEndFlash = true;

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (requestStatus) {}
                sendRequest(data);

            }
        });
    }
}
